package main.bytedance.zuichangqianzhui;

/**
 * 最长公共前缀
 * @author kejl
 * @version test
 * @date 2020/5/26 23:26
 */
public class LongestCommonPrefix {
    public static void main(String[] args) {
        longestCommonPrefix(new String[]{"flower","flow","flight"});
    }

    /**
     *
     * @param strs
     * @return
     */
    public  static  String longestCommonPrefix(String[] strs) {
        if (strs.length<=0){
            return "";
        }
        int strshortestlength = strs[0].length();
        int strshortestpale =0 ;//取最短的防止错误
        for (int k = 0; k < strs.length; k++) {
            if(strshortestlength>strs[k].length()){
                strshortestpale = k;
            }
        }
        boolean isbreak = false;//是否找到结束
        int strplace = 0;
        String indexstr = strs[strshortestpale];//使用最短进行匹配
        for(int i = 0;i<indexstr.length()&& !isbreak;i++,strplace++){//使用某个字符串来为匹配项
            char start = indexstr.charAt(i);//要匹配的字符串
            //  strplace = i;
            for(int j=0;j<strs.length &&  !isbreak;j++){
                if(start != strs[j].charAt(i)){//必须全部匹配，要不就返回了
                    isbreak = true;
                    break;
                }
            }

            if(isbreak){
                break;
            }
        }

        //System.out.println(indexstr.substring(0,strplace));
        return indexstr.substring(0,strplace);
    }

}
